package zgrjb.snbq.teach_platform.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import zgrjb.snbq.teach_platform.enums.BizCodeEnum;
import zgrjb.snbq.teach_platform.util.JsonData;

import jakarta.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * 全局异常处理器
 * 统一处理异常和优化错误响应
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonData handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常 - URL: {}, 异常信息: {}", request.getRequestURI(), e.getMessage());
        return JsonData.buildResult(e.getBizCodeEnum());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonData handleValidationException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .reduce("", (s1, s2) -> s1.isEmpty() ? s2 : s1 + ", " + s2);
        
        log.warn("参数校验异常 - URL: {}, 异常信息: {}", request.getRequestURI(), errorMessage);
        return JsonData.buildError("参数校验失败: " + errorMessage);
    }

    /**
     * 处理文件上传大小超限异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonData handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e, HttpServletRequest request) {
        log.warn("文件上传超限异常 - URL: {}, 异常信息: {}", request.getRequestURI(), e.getMessage());
        return JsonData.buildError("文件大小超出限制，请上传小于10MB的文件");
    }

    /**
     * 处理数据库异常
     */
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonData handleSQLException(SQLException e, HttpServletRequest request) {
        log.error("数据库异常 - URL: {}, 异常信息: {}", request.getRequestURI(), e.getMessage(), e);
        return JsonData.buildError("数据库操作失败，请稍后重试");
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonData handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常 - URL: {}, 异常信息: {}", request.getRequestURI(), e.getMessage(), e);
        return JsonData.buildError("系统内部错误，请联系管理员");
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonData handleException(Exception e, HttpServletRequest request) {
        log.error("未知异常 - URL: {}, 异常类型: {}, 异常信息: {}", 
                request.getRequestURI(), e.getClass().getSimpleName(), e.getMessage(), e);
        return JsonData.buildError("系统繁忙，请稍后重试");
    }
} 